/*
  @author zenghao0219&wenbin
  @description 用于选定座位后的检测空位逻辑和下单逻辑
  @updateDate 最后更新时间为:2022-03-29
*/
<template>
  <div class="confirm" @click="lockSeat()">
    <div class="dib c-d1" v-show="selectedSeat.length != 0">
      {{ selectedSeat.length }}张
    </div>
    <div class="dib c-d2" v-show="selectedSeat.length != 0">
      ￥{{ this.keepTwoDecimalFull(sale_price) }}
    </div>
    <div class="dib c-d1" v-show="selectedSeat.length != 0">
      省￥{{ this.keepTwoDecimalFull(save_price) }}&nbsp;<i style="text-decoration: line-through">市场价￥{{ this.keepTwoDecimalFull(chPrice) }}</i>
    </div>
    {{ selectedSeat.length != 0 ? "确认" : "请先" }}选座
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    propSelectedSeat: Array,
    propSeatList: Array,
    propIsCheap: Number,
    propServiceFee: String,
    propPlanId: String,
    propsId: String,
    propcId: String,
    xtips: Number,
    proptips: Boolean,
    proptocom: Boolean,
    propfilm_id: String,
    propHallName: String,
    propShowDate: String,
    propShowTime: String,
    propcinema: String,
    propEndTime: String,
    propiscOrder: Boolean
  },
  data () {
    // 这里存放数据
    return {
      selectedSeat: this.propSelectedSeat,
      seatList: this.propSeatList
      // ctocom: true
    }
  },
  // 监听属性 类似于data概念
  computed: {
    chPrice () {
      // 市场原价
      let totalPrice = 0
      let selectedSeat = this.selectedSeat
      for (const iterator of selectedSeat) {
        totalPrice += iterator.price
      }
      return totalPrice
    },
    sale_price () {
      // 售卖价格
      let totalPrice = 0
      let selectedSeat = this.selectedSeat
      for (const iterator of selectedSeat) {
        totalPrice += iterator.sale_price
      }
      return totalPrice
    },
    save_price () {
      // 省多少
      let totalPrice = 0
      let selectedSeat = this.selectedSeat
      for (const iterator of selectedSeat) {
        totalPrice += iterator.save_price
      }
      return totalPrice
    },
    seatIdList () {
      let seatIdList = []
      let selectedSeat = this.selectedSeat
      for (const iterator of selectedSeat) {
        seatIdList.push(iterator.seatNo)
      }
      return seatIdList
    },
    selseatList () {
      let selseatList = []
      let selectedSeat = this.selectedSeat
      for (const iterator of selectedSeat) {
        selseatList.push({ 'row': iterator.gRow, 'col': iterator.gCol })
      }
      return selseatList
    }
  },
  // 监控data中的数据变化
  watch: {
    propSelectedSeat: function () {
      this.selectedSeat = this.propSelectedSeat
    },
    propSeatList: function () {
      this.seatList = this.propSeatList
    },
    propIsCheap: function (value) {
      this.isCheap = value
    },
    propServiceFee: function (value) {
      this.serviceFee = value
    },
    propPlanId: function (value) {
      this.planId = value
    },
    propiscOrder: function () {
      console.log('11', this.propiscOrder)
      if (this.propiscOrder) {
        this.createOrder()
      } else {
        alert('下单参数异常~')
      }
    }
  },
  // 方法集合
  methods: {
    lockSeat: function () {
      let _this = this
      // 防止连点
      let check = _this.$once(new Date().getTime())
      if (!check) {
        return
      }
      if (_this.selectedSeat.length === 0) {
        alert('请至少选择一个座位~')
        return
      }
      // 开始计算是否留下空位 ------------ 开始
      // let result = _this.selectedSeat.every(function (element, index, array) {
      //   return _this.checkSeat(element)
      // })
      // 开始计算是否留下空位 ------------ 结束
      // if (!result) {
      //   // 如果 result 为false
      //   alert('请不要留下空位~')
      // } else {
      if (_this.chPrice === 0) {
        alert('锁座失败了~,金额为0')
        return
      }
      console.log(1)
      // this.$emit('ctocom', this.ctocom)
      this.$emit('ctocom', true)
      // 允许锁座
      // this.createOrder()
      // }
    },
    createOrder () {
      this.xtips = this.proptips ? 1 : 0
      console.log('--->', this.xtips)

      // this.$post('https://域名/api/movie.order/create', { show_id: this.propsId, buy_seats: this.selseatList, accept_change_seat: this.xtips }, { emulateJSON: true })
      //   .then((response) => {
      //     console.log('--->>>', response)
      //     // window.location.href = "{:url('/mp/movie/pay')}?sid=" + this.propsId
      //   }).catch((response) => {

      //   })
      // this.$post('https://域名/mp/movie/pay.html', { show_id: this.propsId, buy_seats: this.selseatList, accept_change_seat: this.xtips, seatIdList: this.seatIdList }, { emulateJSON: true })
      //   .then((response) => {
      //     // console.log('--->>>', response)
      //     console.log('--->>>xxx')
      //   }).catch((response) => {

      //   })
      localStorage.setItem('show_id', this.propsId)
      localStorage.setItem('cinema_id', this.propcId)
      localStorage.setItem('buy_seats', JSON.stringify(this.selseatList))
      localStorage.setItem('accept_change_seat', this.xtips)
      localStorage.setItem('seatIdList', JSON.stringify(this.seatIdList))
      localStorage.setItem('seatconunt', this.selectedSeat.length)
      localStorage.setItem('ssyy', this.propcinema)
      localStorage.setItem('sscc', this.propShowDate + '  ' + this.propShowTime)
      localStorage.setItem('ssting', this.propHallName)
      localStorage.setItem('shifu', this.keepTwoDecimalFull(this.sale_price))
      localStorage.setItem('shengxia', this.keepTwoDecimalFull(this.save_price))
      localStorage.setItem('jssj', this.propEndTime)
      console.log('已选座位--->>>', this.selseatList)
      // alert('在这里开始走锁座逻辑，已选座位：' + this.selectedSeat.length)
      window.location.href = 'https://' + window.location.host + '/mp/newmovie/pay.html?id=' + this.propfilm_id
    },
    // 检查每个座位是否会留下空位
    checkSeat: function (element) {
      // 标准为 1.左右侧都必须保留 两格座位 + 最大顺延座位(也就是已选座位减去自身)
      // 2.靠墙和靠已售的座位一律直接通过
      const checkNum = 2 + this.selectedSeat.length - 1
      const gRowBasic = element.gRow
      const gColBasic = element.gCol
      let otherLoveSeatIndex = element.otherLoveSeatIndex
      if (otherLoveSeatIndex != null) {
        // 如果是情侣座 不检测
        return true
      }
      // 检查座位左侧
      let left = this.checkSeatDirection(gRowBasic, gColBasic, checkNum, '-')
      // 如果左侧已经检查出是靠着过道直接 返回true
      if (left === 'special') {
        return true
      }
      // 检查座位右侧
      let right = this.checkSeatDirection(gRowBasic, gColBasic, checkNum, '+')
      if (right === 'special') {
        // 无论左侧是否是什么状态 检查出右侧靠着过道直接 返回true
        return true
      } else if (right === 'normal' && left === 'normal') {
        // 如果左右两侧都有富裕的座位 返回true
        return true
      } else if (right === 'fail' || left === 'fail') {
        // 如果左右两侧都是不通过检测 返回false
        return false
      }
      return true
    },
    // 检查左右侧座位满足规则状态
    checkSeatDirection: function (gRowBasic, gColBasic, checkNum, direction) {
      // 空位个数
      let emptySeat = 0
      let x = 1 // 检查位置 只允许在x的位置出现过道,已售,维修
      for (let i = 1; i <= checkNum; i++) {
        let iter // 根据 gRow gCol direction 找出检查座位左边按顺序排列的checkNum
        if (direction === '-') {
          iter = this.seatList.find((el) => (el.gRow === gRowBasic && el.gCol === gColBasic - i))
        } else if (direction === '+') {
          iter = this.seatList.find((el) => (el.gRow === gRowBasic && el.gCol === gColBasic + i))
        }
        if (x === i) {
          if (iter === undefined) {
          // 过道
            return 'special'
          }
          if (iter.nowIcon === iter.soldedIcon || iter.nowIcon === iter.fixIcon) {
          // 已售或者维修
            return 'special'
          }
          if (iter.nowIcon === iter.selectedIcon) {
          // 已选 顺延一位
            x++
            continue
          }
        } else {
          if (iter === undefined) {
          // 过道
            return 'fail'
          }
          if (iter.nowIcon === iter.soldedIcon ||
              iter.nowIcon === iter.fixIcon ||
              iter.nowIcon === iter.selectedIcon) {
          // 已售或者维修
            return 'fail'
          }
        }
        emptySeat++
        if (emptySeat >= 2) {
          return 'normal'
        }
      }
    },
    // 四舍五入保留2位小数（不够位数，则用0替补）
    keepTwoDecimalFull: function (num) {
      let result = parseFloat(num)
      if (isNaN(result)) {
        // alert('传递参数错误，请检查！')
        return false
      }
      result = Math.round(num * 100) / 100
      let sxa = result.toString() // 将数字转换为字符串
      let posdecimal = sxa.indexOf('.') // 小数点的索引值
      // 当整数时，posdecimal=-1 自动补0
      if (posdecimal < 0) {
        posdecimal = sxa.length
        sxa += '.'
      }
      // 当数字的长度< 小数点索引+2时，补0
      while (sxa.length <= posdecimal + 2) {
        sxa += '0'
      }
      return sxa
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  // 生命周期 - 更新之后
  updated () {},
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='stylus' rel='stylesheet/stylus' scoped='scoped'>
// @import url(); 引入公共css类
.confirm {
  border-radius: 20px;
  position: fixed;
  bottom: 0;
  z-index: 10;
  width: calc( 100% - 50px );
  // background: linear-gradient(to right, #e32424, #f84a4a);
  background: #f7d429
  line-height: 80px;
  text-align: center;
  color: black;
  font-size: 34px;
  font-weight: bold;
  height: 80px
  margin-bottom: 49px
}

.dib {
  display: inline-block;
}

.c-d1 {
  font-size: 24px;
  margin-right: 5px;
}

.c-d2 {
  font-weight: bold;
  margin-right: 10px;
}
</style>
